package com.cadre.web.controller.officer;

import com.cadre.common.core.domain.model.LoginUser;
import com.cadre.common.utils.R;
import com.cadre.common.utils.SecurityUtils;
import com.cadre.common.utils.annotation.SysLog;
import com.cadre.common.utils.common.GenerateUUID;
import com.cadre.common.utils.oldutil.DateUtil;
import com.cadre.common.utils.oldutil.PageUtils;
import com.cadre.system.domain.officer.*;
import com.cadre.system.service.A19Service;
import com.cadre.system.service.ISysRoleService;
import com.cadre.system.service.PersonRelationService;
import com.cadre.system.service.UnitInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "单位Controller", tags = {"单位接口"})
@RequestMapping({"/unitInfo"})
@RestController
/* loaded from: UnitInfoController.class */
public class UnitInfoController {
    @Autowired
    UnitInfoService unitSer;
    @Resource
    A19Service a19Ser;
    @Resource
    ISysRoleService sysRoleDataService;
    @Resource
    PersonRelationService personRelationService;
//    @Resource
//    SysRoleService sysRoleService;

    @RequestMapping({"/getChildListForPage"})
    public R getChildListForPage(@RequestParam Map<String, Object> map) {
        PageUtils pageUtils = this.unitSer.getChildListForPage(map);
        return R.ok().put("page", (Object) pageUtils);
    }

    @GetMapping({"/getUnitInfoById"})
    @ApiOperation("获取干部")
    public R getUnitInfoById(String flowid) {
        return R.ok().put("data", (Object) this.unitSer.getUnitInfoById(flowid));
    }

    @GetMapping({"/LeaderNumber"})
    @ApiOperation("获取领导职数")
    public R LeaderNumber(@RequestParam("unitId") String unitId) {
        return this.unitSer.LeaderNumber(unitId);
    }

    @RequestMapping({"WorkNum"})
    public R WorkNum(@RequestParam("unitId") String unitId) {
        return this.unitSer.WorkNum(unitId);
    }

    @RequestMapping({"getLeaderNums"})
    public R getLeaderNums(@RequestParam("unitIds") String unitIds) {
        return this.unitSer.LeaderNumbers(unitIds);
    }

    @RequestMapping({"getWorkNums"})
    public R getWorkNums(@RequestParam("unitIds") String unitIds) {
        return this.unitSer.WorkNums(unitIds);
    }

    @GetMapping({"/getB0120"})
    @ApiOperation("获取单位级别字典")
    public List<Cadre_dictionary> getB0120(@RequestParam String key) {
        return this.unitSer.getB0120("unit_level_code");
    }

    @GetMapping({"/getB0122"})
    @ApiOperation("获取机构类别字典")
    public List<Tree> getB0122() {
        return this.unitSer.getB0122();
    }

    @GetMapping({"/getB0122s"})
    @ApiOperation("获取机构类别字典")
    public List<ITree> getB0122s() {
        List<Tree> trees= this.unitSer.getB0122();
        List<ITree> iTrees = new ArrayList<>();
        for (Tree tree : trees) {
            boolean flag = true;
            for (Tree tree1 : trees) {
                if(null != tree.getPid() && tree.getPid().equals(tree1.getId())){
                    flag = false;
                }
            }
            if(flag){
                ITree iTree = new ITree();
                iTree.setIcon(tree.getIcon());
                iTree.setIconClose(tree.getIconClose());
                iTree.setName(tree.getName());
                iTree.setId(tree.getId());
                iTree.setPid(tree.getPid());
                iTree.setRwflag(tree.getRwflag());
                iTree.setUnitcode(tree.getUnitcode());
                iTrees.add(iTree);
            }
        }
        iTrees = getITreeList(iTrees,trees);
        return iTrees;
    }
    public List<ITree> getITreeList(List<ITree> itrees,List<Tree> trees){
        if(null != itrees && itrees.size()>0){
            for(ITree iTree:itrees){
                List<ITree> children = new ArrayList<>();
                for(Tree tree: trees){
                    if(iTree.getId().equals(tree.getPid())){
                        ITree iTree1 = new ITree();
                        iTree1.setIcon(tree.getIcon());
                        iTree1.setIconClose(tree.getIconClose());
                        iTree1.setName(tree.getName());
                        iTree1.setId(tree.getId());
                        iTree1.setPid(tree.getPid());
                        iTree1.setRwflag(tree.getRwflag());
                        iTree1.setUnitcode(tree.getUnitcode());
                        children.add(iTree1);
                    }
                }
                if(null != children && children.size()>0){
                    getITreeList(children,trees);
                    iTree.setChildren(children);
                }
            }
        }
        return itrees;
    }

    @GetMapping({"/getB0118"})
    @ApiOperation("所在政区字典")
    public List<Tree> getB0118() {
        return this.unitSer.getB0118();
    }

    @PostMapping({"/addUnit"})
    @SysLog(value = "新增单位信息", target = "B01", set = "B01", type = 0)
    @ApiOperation("添加单位")
    @Transactional
    public R addUnit(@RequestBody B01 b) {
        Map<String, Object> map = new HashMap<>();
        map.put("b0101", b.getB0101());
        map.put("parentid", b.getParentid());
        if (this.unitSer.selectByMaps(map).size() > 0) {
            return R.ok("已存在该单位名称!");
        }
        String flowid = GenerateUUID.getUUID();
        b.setFlowid(flowid);
        if (b.getParentid() != null) {
            b.setUnitcode(getUnitCode(b.getParentid()));
        }
        if (b.getParentid() == null || b.getParentid().isEmpty()) {
            b.setParentid(GenerateUUID.getUUID());
        }
        short serial = 99;
        try {
            serial = Short.parseShort(b.getUnitcode().substring(b.getUnitcode().length() - 2));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        b.setSerial(Short.valueOf(serial));
        this.unitSer.addUnit(b);
        SysRoleDataEntity s = new SysRoleDataEntity();
        LoginUser user = SecurityUtils.getLoginUser();
        s.setFlowid(GenerateUUID.getUUID());

        s.setRoleid(SecurityUtils.getLoginUser().getUser().getRoleId());//todo 需要将角色信息查出来放进去
        s.setUnitid(flowid);
        s.setRwflag("2");
        this.sysRoleDataService.insertSysRoleData(s);//todo:需要理解逻辑，将代码重新编写。


//        for (Object roleId : this.sysRoleService.selectObjs(new EntityWrapper().setSqlSelect("ROLE_ID").ne("ROLE_ID", user.getCurrentRoleId()))) {
//            SysRoleDataEntity entity = new SysRoleDataEntity();
//            entity.setFLOWID(GenerateUUID.getUUID());
//            entity.setROLEID(Long.valueOf(((BigDecimal) roleId).longValue()));
//            entity.setUNITID(flowid);
//            entity.setRWFLAG("1");
//        }//todo: 上面这段for循环代码没看到作用，暂时删除掉
        return R.ok().put("flowid", (Object) flowid);
    }

    @PostMapping({"/addVueUnit"})
    @SysLog(value = "新增单位信息", target = "B01", set = "B01", type = 0)
    @ApiOperation("添加单位")
    @Transactional
    public R addVueUnit(@RequestBody Map<String,Object> param) {
        this.unitSer.saveVueUnit(param);
        return R.ok();
    }

    @PostMapping({"/updateUnit"})
    @SysLog(value = "编辑单位信息", target = "B01", set = "B01", type = 1)
    @ApiOperation("更新单位")
    public R updateUnit(@RequestBody B01 b) {
        if (b.getFlowid().equals(b.getParentid())) {
            return R.ok("不能选择修改单位本单位作为父级单位!");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("b0101", b.getB0101());
        map.put("parentid", b.getParentid());
        map.put("notflowid", b.getFlowid());
        List<B01> repeatList = this.unitSer.selectByMaps(map);
        if (repeatList != null && repeatList.size() > 0) {
            return R.ok("保存失败，同一节点下不能存在相同名称!");
        }
        B01 b1 = (B01) this.unitSer.getById(b.getFlowid());
        B01 pEntity = (B01) this.unitSer.getById(b1.getParentid());
        if (b.getParentid() == null || b.getParentid().isEmpty()) {
            if (pEntity == null) {
            }
        } else if (pEntity == null) {
            b.setUnitcode(getUnitCode(b.getParentid()));
        } else if (!b.getParentid().equals(b1.getParentid())) {
            b.setUnitcode(getUnitCode(b.getParentid()));
        }
        if (b.getPdacode() == "") {
            this.unitSer.updatePdaCode(b);
        } else if (b1.getPdacode() != null) {
            b.setPdacode(null);
        }
        if (b.getParentid() == null || b.getParentid().isEmpty()) {
            b.setParentid(GenerateUUID.getUUID());
        }
        short serial = 99;
        try {
            serial = Short.parseShort(b.getUnitcode().substring(b.getUnitcode().length() - 2));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        b.setSerial(Short.valueOf(serial));
        if (!this.unitSer.saveOrUpdate(b)) {
            return R.ok("保存失败!");
        }
        try {
            this.unitSer.updateNavigatDeptUnitcode();
        } catch (Exception ex2) {
            ex2.printStackTrace();
        }
        return R.ok("保存成功!");
    }

    @PostMapping({"/updateVueUnit"})
    @SysLog(value = "编辑单位信息", target = "B01", set = "B01", type = 1)
    @ApiOperation("更新单位")
    public R updateVueUnit(@RequestBody Map<String,Object> param) {
        unitSer.updateVueUnit(param);
        return R.ok("保存成功!");
    }

    @PostMapping({"/delUnit"})
    @SysLog(value = "删除单位信息", target = "B01", set = "B01", type = DateUtil.SUB_MONTH)
    @ApiOperation("单位删除")
    public R delUnit(@RequestBody String[] unitid) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < unitid.length; i++) {
            if (this.a19Ser.selectListByUnit(unitid[i]).size() > 0) {
                return R.ok("请先调整单位及子单位下的人员!");
            }
            list.add(unitid[i]);
        }
        if (SecurityUtils.getUserId().longValue() != 1) {
            String result = "1";
            int i2 = 0;
            while (true) {
                if (i2 >= unitid.length) {
                    break;
                } else if (this.a19Ser.checkAuthByUnitid(SecurityUtils.getUserId().toString(), unitid[i2]).equals("0")) {
                    result = "0";
                    break;
                } else {
                    i2++;
                }
            }
            if (!result.equals("1")) {
                return R.error("选中数据存在非主管权限数据，终止删除！");
            }
        }
        if (this.unitSer.deleteBatchIdsChild(list)) {
            return R.ok("删除成功!");
        }
        return R.ok("删除失败!");
    }

    @GetMapping({"/getSexProport"})
    @ApiOperation("性别比例")
    public List<Chart> getSexProport(@RequestParam("unitId") String unitId) {
        return this.unitSer.getSexProport(unitId);
    }

    @GetMapping({"/getAgeProport"})
    @ApiOperation("年龄比例")
    public List<Chart> getAgeProport(@RequestParam("unitId") String unitId) {
        return this.unitSer.getAgeProport(unitId);
    }

    @GetMapping({"/getEducationProport"})
    @ApiOperation("学历比例")
    public List<Chart> getEducationProport(@RequestParam("unitId") String unitId) {
        return this.unitSer.getEducationProport(unitId);
    }

    @GetMapping({"/getMajorProport"})
    @ApiOperation("专业比例")
    public List<Chart> getMajorProport(@RequestParam("unitId") String unitId) {
        return this.unitSer.getMajorProport(unitId);
    }

    @GetMapping({"/getsourceProport"})
    @ApiOperation("来源比例")
    public List<Chart> getsourceProport(@RequestParam("unitId") String unitId) {
        return this.unitSer.getsourceProport(unitId);
    }

    @GetMapping({"/getteamMembers"})
    @ApiOperation("班子成员信息列表")
    public R getteamMembers(@RequestParam("unitId") String unitId) {
        return R.ok().put("data", (Object) this.unitSer.getteamMembers(unitId));
    }

    @RequestMapping({"exportExcel"})
    public void exportExcel(@RequestParam("unitId") String unitId, HttpServletRequest request, HttpServletResponse response) {
        this.unitSer.exportExcel(unitId, request, response);
    }

    @RequestMapping({"exportExcel2"})
    public void exportExcel2(@RequestParam("unitId") String unitId, HttpServletRequest request, HttpServletResponse response) {
        this.unitSer.exportExcel2(unitId, request, response);
    }

    @RequestMapping({"orderUnit"})
    public R orderUnit(@RequestParam Map<String, Object> map) {
        String str = this.unitSer.orderUnit(map);
        try {
            this.unitSer.updateNavigatDeptUnitcode();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return R.ok(str);
    }

    @RequestMapping({"orderUnitPdacode"})
    public R orderUnitPdacode(@RequestParam Map<String, Object> map) {
        return R.ok(this.unitSer.orderUnitPdacode(map));
    }

    @RequestMapping({"saveUnitPdacode"})
    public R saveUnitPdacode(@RequestBody List<String> list) {
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                try {
                    String[] info = list.get(i).split("_");
                    String unitid = info[0];
                    String pdacode = "";
                    try {
                        pdacode = info[1];
                    } catch (Exception e) {
                    }
                    Map<String, Object> pMap = new HashMap<>();
                    pMap.put("unitid", unitid);
                    pMap.put("pdacode", pdacode);
                    this.unitSer.updatePdaCodeByMap(pMap);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return R.ok("同步完毕");
    }

    @GetMapping({"personRelation"})
    @ApiOperation("班子成员人物关系")
    public R personRelation(@RequestParam("unitId") String unitId) {
        return R.ok().put("personRelation", (Object) this.personRelationService.getBzRelation(unitId));
    }

    @GetMapping({"initB01Actual"})
    @ApiOperation("班子真实职数初始化")
    public R initB01Actual() {
        this.unitSer.initB01Actual();
        return R.ok("班子真实职数初始化完成！！！");
    }

    @PostMapping({"syncPDAOrder"})
    @ApiOperation("PDA顺序同步")
    public R syncPDAOrder() {
        this.unitSer.syncPDAOrder();
        return R.ok("同步完成！！！");
    }

    @GetMapping({"initB01UnitCode"})
    @ApiOperation("初始化unitcode")
    public R initB01UnitCode() {
        this.unitSer.syncPDAOrder();
        try {
            this.unitSer.updateNavigatDeptUnitcode();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return R.ok("unitcode初始化完成！！！");
    }

    private String getUnitCode(String parentid) {
        String maxCode = this.unitSer.getMaxCode(parentid);
        if (((B01) this.unitSer.getById(parentid)) == null) {
            maxCode = this.unitSer.getMaxCodeLenTwo();
        }
        if (maxCode == null || maxCode.length() < 2) {
            B01 b = (B01) this.unitSer.getById(parentid);
            if (b == null || b.getUnitcode() == null) {
                return "01";
            }
            return b.getUnitcode() + "01";
        }
        int i = Integer.parseInt(maxCode.substring(maxCode.length() - 2, maxCode.length())) + 1;
        if (i < 10) {
            if (maxCode.length() == 2) {
                return "0" + i;
            }
            return maxCode.substring(0, maxCode.length() - 2) + "0" + i;
        } else if (maxCode.length() == 2) {
            return "" + i;
        } else {
            return maxCode.substring(0, maxCode.length() - 2) + i;
        }
    }
}
